import { SafeAreaView, StyleSheet, Text, View, VirtualizedList, Image, TouchableWithoutFeedback, TouchableOpacity, ActivityIndicator, LogBox } from 'react-native'
import React, { createRef, useRef, useState, useCallback, useEffect, memo, useImperativeHandle } from 'react'
import { pTx } from "../../utils/dimensions"
import httpApi from "../../api"
import { grade } from "../../utils/grade"
import { useNavigation } from '@react-navigation/native';
import ImageEquallyEnlarge from "../../components/imageEquallyEnlarge"
import ImageView from "react-native-image-viewing";

LogBox.ignoreLogs([
    'Non-serializable values were found in the navigation state',
]);
const ImageViewModule = memo(({ images }) => {
    const [visible, setVisible] = useState(false)
    const [imageIndex, setImageIndex] = useState(false)
    const list = images?.split(',').map(item => { return { uri: httpApi.inline + item } })
    return <>
        {
            list.map((img, i) => {
                return (
                    <TouchableOpacity
                        onPress={() => {
                            setVisible(true)
                            setImageIndex(i)
                        }}
                        key={i}
                    >
                        <View>

                            {
                                list.length == 1 ?
                                    <ImageEquallyEnlarge
                                        source={img}
                                        width={pTx(220)}
                                    />
                                    :
                                    <Image
                                        style={[styles.ContentImageItem]}
                                        source={img}></Image>
                            }
                        </View>
                    </TouchableOpacity>
                )
            })
        }
        <ImageView
            images={list}
            imageIndex={imageIndex}
            visible={visible}
            onRequestClose={() => setVisible(false)}
        />
    </>
})



const renderLoadMoreView = (data, total, loading) => {
    return <View style={styles.loadMore}>
        {data.length < total.current || loading.current ?
            <>
                <ActivityIndicator
                    style={styles.indicator}
                    size={"small"}
                    color={"rgba(6, 193, 97, 1)"}
                    animating={true}
                />
                <Text>正在加载更多</Text>
            </>
            : <View >
                <Text>没有更多了</Text>
            </View>
        }
    </View>
}
const getItem = (item, index) => {
    return item[index]
}

const PostLike = React.forwardRef(({ item, onPostLike }, ref) => {
    const [Likes, setLikes] = useState(item.Likes)
    const [IsLike, setIsLike] = useState(item.IsLike)
    const [loading, setLoading] = useState(false)
    const send = async () => {
        try {
            if (IsLike >= 1) {
                setLikes(Likes - 1)
                setIsLike(0)
            } else {
                setLikes(Likes + 1)
                setIsLike(1)
            }
            setLoading(true)
            await httpApi.postLike({ postId: item.Id })
        } catch (error) {
        }
        setLoading(false)
    }
    useEffect(() => {
        if (loading) {
            onPostLike(item, Likes, IsLike)
        }
    }, [loading])
    const set = (Likes, IsLike) => {
        setLikes(Likes)
        setIsLike(IsLike)
    }
    useImperativeHandle(ref, () => ({
        set,
    }))
    return <TouchableOpacity onPress={() => send(item)}>
        <View style={styles.CommentsQuantityObxCell}>
            <Image style={styles.CommentsIcon} source={IsLike ? require('../../assets/image/icon16-a.png') : require('../../assets/image/icon16.png')}></Image>
            <Text style={styles.postCommentValue}>{Likes}</Text>
        </View>
    </TouchableOpacity>
})
const PostFavorite = React.forwardRef(({ item, onPostFavorite }, ref) => {
    const [Favorites, setFavorites] = useState(item.Favorites)
    const [IsFavorite, setIsFavorite] = useState(item.IsFavorite)
    const [loading, setLoading] = useState(false)
    const send = async () => {
        try {
            if (IsFavorite >= 1) {
                setFavorites(Favorites - 1)
                setIsFavorite(0)
            } else {
                setFavorites(Favorites + 1)
                setIsFavorite(1)
            }
            setLoading(true)
            await httpApi.postFavorite({ postId: item.Id })
        } catch (error) {
        }
        setLoading(false)
    }
    useEffect(() => {
        if (loading) {
            onPostFavorite(item, Favorites, IsFavorite)
        }
    }, [loading])
    const set = (Favorites, IsFavorite) => {
        setFavorites(Favorites)
        setIsFavorite(IsFavorite)
    }
    useImperativeHandle(ref, () => ({
        set,
    }))
    return <TouchableOpacity onPress={() => send(item)}>
        <View style={styles.CommentsQuantityObxCell}>
            <Image style={styles.CommentsIcon} source={IsFavorite ? require('../../assets/image/icon18-a.png') : require('../../assets/image/icon18.png')}></Image>
            <Text style={styles.postCommentValue}>{Favorites}</Text>
        </View>
    </TouchableOpacity>
})


const Recommend = memo((props) => {
    const [data, setData] = useState([]); // 
    const total = useRef(0)
    const pageNum = useRef(0)
    const pageSize = useRef(30)
    const loading = useRef(true);
    const PostLikeRefs = useRef([]);
    const PostFavoriteRefs = useRef([]);
    const [refreshing, setRefreshing] = useState(false);
    const releasePostRefs = useRef()
    const navigation = useNavigation();

    const fetchData = useCallback(async (Refreshing) => {
        try {
            loading.current = true
            const res = await httpApi.getPostList({ pageNum: pageNum.current, pageSize: pageSize.current })
            loading.current = false
            if (Refreshing) {
                setData(res.data.PostList);

            } else {
                setData(prevData => [...prevData, ...res.data.PostList]);
            }
            total.current = res.data.Total
            pageNum.current += 1;
        } catch (error) {
        }
    }, [data]);

    useEffect(() => {
        fetchData()
    }, [])

    // 上拉加载更多
    const loadMore = () => {
        if (!loading.current && data.length < total.current) {
            fetchData();
        } else {
            loading.current = false
        }
    };

    // 下拉刷新
    const refreshList = () => {
        // setRefreshing(true)
        pageNum.current = 0
        fetchData(true).then(() => {
            // setRefreshing(false)
        });
    };

    const onPostLike = useCallback((item, Likes, IsLike) => {
        setData(prev => prev.map((element, idx) => {
            if (element.Id === item.Id) {
                element.Likes = Likes
                element.IsLike = IsLike
                return element
            } else {
            }
            return element
        }))
    })

    const onPostFavorite = useCallback((item, Favorites, IsFavorite) => {
        setData(prev => prev.map((element, idx) => {
            if (element.Id === item.Id) {
                element.Favorites = Favorites
                element.IsFavorite = IsFavorite
                return element
            } else {
            }
            return element
        }))
    })

    const onFollow = useCallback((item, IsFollow) => {
        setData(prev => prev.map((element, idx) => {
            if (element.Id === item.Id) {
                element.IsFollow = IsFollow
                return element
            } else {
            }
            return element
        }))
    })

    const renderItem = ({ item, index }) => {
        if (!PostLikeRefs.current[index]) {
            PostLikeRefs.current[index] = React.createRef();
        }
        if (!PostFavoriteRefs.current[index]) {
            PostFavoriteRefs.current[index] = React.createRef();
        }
        return (
            <View style={styles.renderItemli} >
                <Image style={styles.ProfilePhoto} source={{ uri: httpApi.inline + item.ProfilePhoto }}></Image>
                <View style={styles.PostContainer}>
                    <TouchableOpacity onPress={() => navigation.navigate('commentsList', {
                        ...item, PostLike: PostLikeRefs.current[index], PostFavorite: PostFavoriteRefs.current[index], onFollow
                    })}>
                        <View>
                            <View style={styles.PostContainerUserInfo}>
                                <View style={styles.infoCotent}>
                                    <Text style={styles.NickName}>{item.NickName}</Text>
                                    {/* <Image style={styles.infoCotentImage} source={grade[item.UserLevel]}></Image> */}
                                </View>
                                <Text style={styles.timr}  >{item.CreatedAt}</Text>
                            </View>
                            <View style={styles.ContentInfo}>
                                {item.Content ? <Text style={styles.Content}>{item.Content}</Text> : ""}
                                {item.Image && <View style={styles.ContentImageList}>
                                    <ImageViewModule images={item.Image} />
                                </View>}
                            </View>
                        </View>
                    </TouchableOpacity>
                    <View style={styles.CommentsQuantityObx}>
                        <PostLike ref={PostLikeRefs.current[index]} item={item} onPostLike={onPostLike} />
                        <TouchableOpacity onPress={() => navigation.navigate('commentsList', {
                            ...item, PostLike: PostLikeRefs.current[index], PostFavorite: PostFavoriteRefs.current[index], onFollow
                        })}>
                            <View style={styles.CommentsQuantityObxCell}>
                                <Image style={styles.CommentsIcon} source={require('../../assets/image/icon17.png')}></Image>
                                <Text style={styles.postCommentValue}>{item.Comments}</Text>
                            </View>
                        </TouchableOpacity>
                        <PostFavorite ref={PostFavoriteRefs.current[index]} item={item} onPostFavorite={onPostFavorite} />
                    </View>
                </View>
            </View>
        )
    }

    return (
        <>
            <VirtualizedList
                data={data}
                initialNumToRender={10}
                refreshing={refreshing}
                getItemCount={() => data.length}
                keyExtractor={(item, index) => index}
                getItem={getItem}
                renderItem={renderItem}
                onEndReached={loadMore}
                onRefresh={refreshList}
                ListFooterComponent={() => renderLoadMoreView(data, total, loading)}
            />
            <TouchableOpacity style={styles.release} onPress={() => navigation.navigate('releasePost')}>
                <Image style={styles.releaseImage} source={require('../../assets/image/release.png')}></Image>
            </TouchableOpacity>
        </>
    )
})

export default Recommend


const styles = StyleSheet.create({
    loadMore: {
        alignItems: "center",
        paddingVertical: pTx(10)
    },
    indicator: {
        paddingBottom: pTx(5),
    },

    release: {
        position: "absolute",
        bottom: pTx(14),
        right: pTx(3),
    },
    releaseImage: {
        width: pTx(74),
        height: pTx(74),
    },

    renderItemli: {
        marginTop: pTx(16),
        flexDirection: 'row',
        paddingHorizontal: pTx(15),
    },
    ProfilePhoto: {
        width: pTx(41),
        height: pTx(41),
        backgroundColor: "#EDEDED",
        borderRadius: pTx(6),
    },
    PostContainer: {
        marginLeft: pTx(8),
    },
    infoCotent: {
        flexDirection: 'row',
        alignItems: "center"
    },
    infoCotentImage: {
        width: pTx(34),
        height: pTx(16),
    },
    NickName: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    timr: {
        marginTop: pTx(7),
        fontSize: pTx(12),
        color: "#AFB5BD",
    },
    ContentInfo: {
        marginTop: pTx(13),
        maxWidth: pTx(290)
    },
    Content: {
        fontSize: pTx(15),
        color: "#0A0C14"
    },
    ContentImageList: {
        marginTop: pTx(8),
        flexDirection: 'row',
        flexWrap: "wrap",
        width: pTx(290)
    },
    ContentImageItem: {
        width: pTx(90),
        height: pTx(90),
        marginRight: pTx(5),
        marginBottom: pTx(5),
        borderRadius: pTx(4),
        backgroundColor: "#EDEDED",
    },
    postComment: {
        marginTop: pTx(10),
        width: pTx(296),
        paddingVertical: pTx(6),
        backgroundColor: "rgba(237,237,237,0.3)",
        borderRadius: pTx(3),
    },
    postCommentCell: {
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(6),
        fontSize: pTx(14),
        color: "#0A0C14"
    },
    CommentsQuantityObx: {
        marginTop: pTx(12),
        paddingBottom: pTx(16),
        flexDirection: 'row',
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1,
    },
    CommentsQuantityObxCell: {
        flexDirection: 'row',
        alignItems: "center",
        marginRight: pTx(32),
    },
    CommentsIcon: {
        marginRight: pTx(3),
        width: pTx(14),
        height: pTx(14),
        padding: pTx(1),
    },
    postCommentValue: {
        fontSize: pTx(10),
        color: "#A6A8B3"
    }
})